<?php
/* This file is part of LlamaSlayers Ajax Chat
 *
 * The source code is released under the GNU GPL free software license, version 3.
 * Updates can be found at http://llamaslayers-ajax-chat.googlecode.com/
 */

require_once dirname( __FILE__ ) . '/config.php';

session_start();

if ( empty( $_GET['room'] ) || !trim( $_GET['room'] ) )
	$_GET['room'] = 'public';

$_GET['room'] = preg_replace( '/[^a-z0-9_\-]/', '', strtolower( trim( $_GET['room'] ) ) );

function downto32( $a ) {
	return substr( $a, 1, 32 );
}

if ( !file_exists( dirname( __FILE__ ) . '/db/online/' . $_GET['room'] . '.txt' ) )
	exit;

if ( empty( $_SESSION['name'] ) || !in_array( md5( $_SERVER['HTTP_USER_AGENT'] . '@' . $_SERVER['REMOTE_ADDR'] ), array_map( 'downto32', file( dirname( __FILE__ ) . '/db/online/' . $_GET['room'] . '.txt' ) ) ) )
	exit;

$fp = fopen( dirname( __FILE__ ) . '/db/chat/' . $_GET['room'] . '.txt', 'a' );
$message = preg_replace( '/\s\s+/', ' ', trim( stripslashes( $_GET['message'] ) ) );

if ( strlen( $message ) ) {
	if ( $_SESSION['authenticated'] ) {
		$user = file( dirname( __FILE__ ) . '/db/user/' . $_SESSION['authenticated'] . '.txt' );
		fwrite( $fp, "\n*" . str_pad( rtrim( $user[2] ), 31, '*', STR_PAD_LEFT ) . urlencode( str_ireplace( $censored_words, 'BANANAS', $_SESSION['name'] ) ) . ':' . time() . ':' . urlencode( str_ireplace( $censored_words, 'BANANAS', ' ' . $message ) ) );
	} else {
		fwrite( $fp, "\n" . md5( $_SERVER['HTTP_USER_AGENT'] . '@' . $_SERVER['REMOTE_ADDR'] ) . urlencode( str_ireplace( $censored_words, 'BANANAS', $_SESSION['name'] ) ) . ':' . time() . ':' . urlencode( str_ireplace( $censored_words, 'BANANAS', ' ' . $message ) ) );
	}
	fclose( $fp );
}

?>